﻿using System.Security.Cryptography;
namespace Service.Utity
{
    public enum RSAKeyType
    {
        PubKey,
        PriKey
    }
    public static class RSAStore
    {
        /// <summary>
        ///  通过文件路径加载RSA
        ///  通过RSA.Create(),拿到的随机密钥 Base64编码，公钥私钥分别写入文件
        ///  公钥仅用于加密，私钥可用于解密
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="RSAKeyType">密钥类型，公钥私钥</param>
        /// <returns></returns>
        public static (RSA? Result,string message) GetRSA()
        {
            try
            {
                RSA result = RSA.Create();
                var pubKeyPath = Path.Join(AppDomain.CurrentDomain.BaseDirectory, "secretkey", "pubKey.o");
                if (File.Exists(pubKeyPath))
                { 
                    var pubKeyContent = File.ReadAllText(pubKeyPath);
                    result.ImportRSAPublicKey(Convert.FromBase64String(pubKeyContent),out int _);
                }
                DriveInfo[] drives = DriveInfo.GetDrives();
                bool hasPriKey = false;
                foreach (var drive in drives)
                {
                    string priKeyPath = Path.Join(drive.RootDirectory.FullName, "CertPriKey", "priKey.o");
                    if (File.Exists(priKeyPath))
                    {
                        var priKeyContent = File.ReadAllText(priKeyPath);
                        result.ImportRSAPrivateKey(Convert.FromBase64String(priKeyContent), out int _);
                        hasPriKey = true;
                        break;
                    }
                }
                if (!hasPriKey)
                {
                    return (null, "未找到私钥,请将私钥置于可移动磁盘/CertPriKey下");
                }
                return (result,string.Empty);
            }
            catch (Exception ex)
            {
                return (null, ex.Message);
            }
        }
        /// <summary>
        /// 创建一个RSA
        /// </summary>
        public static bool CreateRsa()
        {
            try
            {
                RSA result = RSA.Create();
                string pubKey = Convert.ToBase64String(result.ExportRSAPublicKey());
                string priKey = Convert.ToBase64String(result.ExportRSAPrivateKey());
                var dirInfo= Directory.CreateDirectory(Path.Join(AppDomain.CurrentDomain.BaseDirectory, "secretkey"));
                if (!File.Exists(Path.Join(dirInfo.FullName, "pubKey.o")))
                {
                    File.WriteAllText(Path.Join(dirInfo.FullName, "pubKey.o"), pubKey);
                    File.WriteAllText(Path.Join(dirInfo.FullName, "priKey.o"), priKey);
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
